from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView

from cart.cartser import CartSerializer, CartSer
from cart.models import CartModel


# Create your views here.

# 加入购物车
class AddCart(APIView):
    def post(self, request):
        goods = request.data.get('goods')
        user = request.data.get('user')
        c_num = request.data.get('c_num')
        cart = CartModel.objects.filter(goods=goods, user=user).first()
        if cart:
            cart.c_num += int(c_num)
            cart.save()
            return Response({"code": 200, "message": "添加成功", })
        else:
            ser = CartSerializer(data=request.data)
            if ser.is_valid():
                ser.save()
                return Response({"code": 200, "message": "添加成功", })
            else:
                return Response({"code": 400, "message": "添加失败", })


# 查看购物车
class CartView(APIView):
    def get(self, request):
        user = request.query_params.get('user')
        cart = CartModel.objects.filter(user=user)
        ser = CartSer(cart, many=True)
        return Response({"code": 200, "data": ser.data})


# 修改购物车斤数
class UpdCart(APIView):
    def put(self, request):
        id = request.data.get('id')
        c_num = request.data.get('c_num')
        cart = CartModel.objects.filter(id=id).first()
        cart.c_num = c_num
        cart.save()
        return Response({"code": 200, "message": "修改成功"})


# 删除单个
class DelOneCart(APIView):
    def delete(self, request):
        id = request.query_params.get('id')
        cart = CartModel.objects.filter(id=id).first()
        cart.delete()
        return Response({"code": 200, "message": "删除成功"})


# 删除选中
class DelSelectCart(APIView):
    def delete(self, request):
        user = request.query_params.get('user')
        CartModel.objects.filter(user=user, select=True).delete()
        return Response({"code": 200, "message": "删除成功"})


# 点击选中
class ChangeOneCart(APIView):
    def put(self, request):
        id = request.data.get('id')
        cart = CartModel.objects.filter(id=id).first()
        cart.select = not cart.select
        cart.save()
        return Response({"code": 200, "message": "选中成功"})


# 全选
class ChangeAllCart(APIView):
    def put(self, request):
        user = request.data.get('user')
        select = request.data.get('select')
        cart = CartModel.objects.filter(user=user)
        for c in cart:
            c.select = select
            c.save()
        return Response({"code": 200, "message": "选中成功"})


class SelectCart(APIView):
    def get(self, request):
        user = request.query_params.get('user')
        cart = CartModel.objects.filter(user=user, select=True)
        ser = CartSer(cart, many=True)
        return Response({"code": 200, "data": ser.data})
